//
//  AQGCDTask.m
//  RunLoopDemo
//
//  Created by zhangjikuan on 2020/11/10.
//  Copyright © 2020 hsgd. All rights reserved.
//


#import "AQGCDTask.h"
/// weak reference for all instances
static NSMapTable *_globalInstances;
static dispatch_semaphore_t _globalInstancesLock;

static void _YYDiskCacheInitGlobal() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _globalInstancesLock = dispatch_semaphore_create(1);
        _globalInstances = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
    });
}
//
//static YYDiskCache *_YYDiskCacheGetGlobal(NSString *path) {
//    if (path.length == 0) return nil;
//    _YYDiskCacheInitGlobal();
//    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
//    id cache = [_globalInstances objectForKey:path];
//    dispatch_semaphore_signal(_globalInstancesLock);
//    return cache;
//}

//static void _YYDiskCacheSetGlobal(YYDiskCache *cache) {
//    if (cache.path.length == 0) return;
//    _YYDiskCacheInitGlobal();
//    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
//    [_globalInstances setObject:cache forKey:cache.path];
//    dispatch_semaphore_signal(_globalInstancesLock);
//}

@implementation AQGCDTask



- (void)execute {
    __block int a = 0;
    
    while (a < 5) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            a ++;
            NSLog(@"里面  a = %d",a);
        });
    }
    
    NSLog(@"外面 a === %d", a);

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"最终 a === %d", a);
    });
    
    dispatch_semaphore_t sem  = dispatch_semaphore_create(1);
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    
    
    dispatch_semaphore_signal(sem);
//    
//    [self dispatch_semaphore_test];
//    [self dispatch_group_test];
    [self dispatch_semaphore_test2];
}

/// 多个网络请求完成后如何执行下一步？

/// 多个网络请求完成后如何执行下一步


- (void)dispatch_group_test {
    NSString *str = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];

    dispatch_group_t downloadGroup = dispatch_group_create();
    for (int i=0; i<10; i++) {
        dispatch_group_enter(downloadGroup);
        
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d---%d",i,i);
            dispatch_group_leave(downloadGroup);
        }];
        [task resume];
    }

    dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
        NSLog(@"end");
    });
}

- (void)dispatch_semaphore_test {
    NSString *str = @"https://www.baidu.com";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *sesson = [NSURLSession sharedSession];
    
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    __block  int count = 0;
    for (int i = 0; i < 10; i ++) {
        NSURLSessionDataTask *task = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSLog(@"%d---%d",i,i);
            count++;
            if (count==10) {
                dispatch_semaphore_signal(sem);
                count = 0;
            }
        }];
        
        [task resume];
        
    }
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"end");
    });
}

// 7.多个网络请求顺序执行后如何执行下一步？

// 使用信号量semaphore
// 每一次遍历，都让其dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)，这个时候线程会等待，阻塞当前线程，直到dispatch_semaphore_signal(sem)调用之后

- (void)dispatch_semaphore_test2 {
    NSString *str = @"http://www.jianshu.com/p/6930f335adba";
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];

    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    for (int i=0; i<10; i++) {
        
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSLog(@"%d---%d",i,i);
            dispatch_semaphore_signal(sem);
        }];
        
        [task resume];
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"end");
    });
}

@end
